//
//  DMScannerAnimationView.swift
//  DigitalMuseum
//
//  Created by zhongshan on 2024/2/21.
//

import UIKit

class DMScannerAnimationView: UIView {

    private let animatedLine: CALayer = {
        let layer = CALayer()
        layer.contents = UIImage(resource: .scannerLine).cgImage
        layer.isHidden = true
        return layer
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weak self] _ in
            guard let self else { return }
            if !isHidden && superview != nil {
                startAnimation()
            }
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func startAnimation() {
        let lineHeight: CGFloat = 30
        animatedLine.frame = CGRect(x: 0, y: -lineHeight, width: frame.width, height: lineHeight)
        layer.addSublayer(animatedLine)
        animatedLine.isHidden = false
        
        let moveAnimation = CABasicAnimation(keyPath: "position")
        moveAnimation.fromValue = NSValue(cgPoint: CGPoint(x: center.x, y: 0))
        moveAnimation.toValue = NSValue(cgPoint: CGPoint(x: center.x, y: frame.height))
        
        let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
        opacityAnimation.values = [0.1, 0.6, 0.1]
        opacityAnimation.keyTimes = [0, 0.5, 1]
        
        let animationGroup = CAAnimationGroup()
        animationGroup.duration = 3
        animationGroup.repeatCount = .infinity
        animationGroup.animations = [moveAnimation, opacityAnimation]
        
        animatedLine.add(animationGroup, forKey: "animationGroup")
    }
    
    func stopAnimation() {
        animatedLine.isHidden = true
        animatedLine.removeAllAnimations()
        animatedLine.removeFromSuperlayer()
    }
    
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        nil
    }
}
